package cn.hello2018.sdk.ftp;

import cn.hello2018.sdk.property.PropertiesUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Ftp上传服务
 *
 * @author jeymingwu
 * @date 2019/3/20 20:19
 */
public class FTPServerUtil {

    private static String ftpIP = PropertiesUtil.getProperty("ftp.server.ip");
    private static String ftpUsername = PropertiesUtil.getProperty("ftp.user");
    private static String ftpPasspass = PropertiesUtil.getProperty("ftp.pass");
    private static Logger logger = LoggerFactory.getLogger(FTPServerUtil.class);
    private String ip;
    private Integer port;
    private String username;
    private String password;
    private FTPClient client;

    public FTPServerUtil(String ip, Integer port, String username, String password) {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public static String getFtpIP() {
        return ftpIP;
    }

    public static void setFtpIP(String ftpIP) {
        FTPServerUtil.ftpIP = ftpIP;
    }

    public static String getFtpUsername() {
        return ftpUsername;
    }

    public static void setFtpUsername(String ftpUsername) {
        FTPServerUtil.ftpUsername = ftpUsername;
    }

    public static String getFtpPasspass() {
        return ftpPasspass;
    }

    public static void setFtpPasspass(String ftpPasspass) {
        FTPServerUtil.ftpPasspass = ftpPasspass;
    }

    /**
     * 上传文件至Ftp服务器
     *
     * @param files 文件名列表
     * @return 处理结果
     */
    public static boolean uploadFile(List<File> files) {
        FTPServerUtil ftpServerUtil = new FTPServerUtil(ftpIP, 21, ftpUsername, ftpPasspass);
        logger.info("开始连接FTP服务器");
        boolean result = ftpServerUtil.uploadFile("/img", files);
        logger.info("上传完成，FTP服务器断开连接，上传结果：{}", result);
        return result;
    }

    /**
     * 将文件从Ftp服务器中删除
     *
     * @param fileName 文件名
     * @return 处理结果
     */
    public static boolean deleteFile(String fileName) {
        FTPServerUtil ftpServerUtil = new FTPServerUtil(ftpIP, 21, ftpUsername, ftpPasspass);
        logger.info("开始连接FTP服务器");
        boolean result = ftpServerUtil.deleteFile("/img", fileName);
        logger.info("删除操作完成，FTP服务器断开连接，结果：{}", result);
        return result;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public FTPClient getClient() {
        return client;
    }

    public void setClient(FTPClient client) {
        this.client = client;
    }

    private boolean uploadFile(String path, List<File> files) {
        boolean uploadFile = false;
        FileInputStream fileInputStream = null;
        // 连接FTP服务器
        if (connectServer(this.getIp(), this.getPort(), this.getUsername(), this.getPassword())) {
            try {
                client.changeWorkingDirectory(path);
                client.setBufferSize(1024);
                client.setControlEncoding("UTF-8"); // 编码
                client.setFileType(FTPClient.BINARY_FILE_TYPE); // 二进制格式
                client.enterLocalPassiveMode(); // 被动模式
                for (File file : files) {
                    fileInputStream = new FileInputStream(file);
                    client.storeFile(file.getName(), fileInputStream);
                }
                uploadFile = true;
            } catch (IOException e) {
                logger.error("上传文件异常", e);
                e.printStackTrace();
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                    client.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return uploadFile;
    }

    private boolean deleteFile(String path, String filename) {
        boolean deleteFile = false;
        if (connectServer(this.getIp(), this.getPort(), this.getUsername(), this.getPassword())) {
            try {
                client.changeWorkingDirectory(path);
                client.deleteFile(filename);
                deleteFile = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    client.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return deleteFile;
    }

    /**
     * 连接Ftp服务器
     *
     * @param host     主机
     * @param port     端口号
     * @param username 用户名
     * @param password 密码
     * @return 连接结果
     */
    private boolean connectServer(String host, Integer port, String username, String password) {
        boolean isSuccess = false;
        client = new FTPClient();
        try {
            client.connect(host, port);
            isSuccess = client.login(username, password);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("连接FTP服务器失败", e);
        }
        return isSuccess;
    }
}
